function varargout = TLIndexsearchDlg(action, varargin)

% TL_INDEXSEARCH_DLG manages the user interface for TargetLink Index Search block
%
% SYNTAX dlgInfo = TLIndexsearchDlg('GetDlgInfo');
%   gets dialog info of TargetLink Index Search block
%
%   INPUT ARGUMENTS
%   -/-
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLIndexsearchDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLIndexsearchDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLIndexsearchDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLIndexsearchDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLIndexsearchDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLIndexsearchDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.20 $
% $Date: 2011/05/12 08:08:23MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action
    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'PreLook-Up Index Search';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames   = {
            'Table';
            'Logging & Autoscaling';
            'Documentation'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'Table'
                [sheetDims, ctrlPos] = FcnCalcTableCtrlPositions(commonGeom);

            case 'Logging & Autoscaling'
                excludedCtrls = {};
                [sheetDims, ctrlPos] = ...
                    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);

            case 'Documentation'
                % block has extra table controls
                bCodeComment = 1;
                bTblBlock = 1;
                [sheetDims, ctrlPos] = ...
                    TLManageDocCtrls('ctrlpos', commonGeom, sheetDims, ...
                    bCodeComment, bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;

    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Table'
                dlgdata = FcnCreateTableCtrls(pageNum, dlgfig, dlgdata);

            case 'Logging & Autoscaling'
                dlgdata =  TLManageLoggingCtrls('create', pageNum, dlgfig, dlgdata);

            case 'Documentation'
                dlgdata = FcnCreateDocumentationCtrls(pageNum, dlgfig, dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Table'
                [dlgdata, bModified] = FcnManageTableCtrls(pageNum, dlgfig, ...
                    dlgdata, pageAction);

            case 'Logging & Autoscaling'
                [dlgdata, bModified] = ...
                    TLManageLoggingCtrls('manage', pageNum, dlgdata, pageAction, 'logdata');

            case 'Documentation'
                [dlgdata, bModified] = FcnManageDocumentationCtrls(pageNum, ...
                    dlgfig, dlgdata, pageAction);
                
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified ;
        
    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;
        
    case 'Update'
        dlgfig    = varargin{1};
        dlgdata   = varargin{2};
        pageNum   = varargin{3};
        
        pageName  = dlgdata.pageNames{pageNum};
        switch pageName
            case 'Table'
                dlgdata = FcnUpdateTableCtrls(pageNum, dlgfig, dlgdata);

            case 'Logging & Autoscaling'
                dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,'logdata','output');
                TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);

            case 'Documentation'
                dlgdata = FcnUpdateDocumentationCtrls(pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action "' action '"']);

end

%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile, blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile, blockstr);
        end
    case 'ViewCode'
        switch dlgdata.pageNames{dlgdata.CurrentPageNum}            
            case 'Table'
                idx = get(dlgdata.pageData{1}.children.selectPopup, 'Value');
                if idx == 1
                    tl_create_links_to_model('ShowDeclaration', dlgdata.model, 'input');
                else
                    tl_create_links_to_model('ShowComputation', dlgdata.model, 'output');
                end
            otherwise
                tl_create_links_to_model('ShowComputation', dlgdata.model, 'output');
        end
    otherwise
        error('Invalid callback');
end


%-----------------------------------------------------------------------------------------
% FcnCalcTableCtrlPositions calculates positions for all controls on table page
%
% INPUT ARGUMENTS
%   commonGeom      common geometry information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCalcTableCtrlPositions(commonGeom)

excludedCtrls = {'saturate', 'inheritproperties', 'scalarExp'};
[sheetDims, ctrlPos, col, colDelta, rowDelta] = ...
    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

strings_and_styles = {...
    'Select:',                    'text'; ...
    'Breakpoint data:',           'text'; ...
    ' Scale Vector ',             'pushbutton'; ...
    'Separate output variables for index and fraction', 'popupmenu'; ...
    'Use value of Data Dictionary variable', 'checkbox'};

[selectLabelSize, ...
    editLabelSize, ...
    autoscaleButtonSize, ...
    outputmodePopupSize, ...
    useDDValueCheckboxSize] = ...
    ds_get_uicontrol_sizes(commonGeom,strings_and_styles);

%-----------------------------------------------------------
% enlarge groupboxes
%-----------------------------------------------------------
% calculate extra space needed for select popup
dy = commonGeom.editHeight + rowDelta;

% enlarge tlcgGroupbox and addoptGroupbox
ctrlPos.tlcgoptGroupbox(4) = ctrlPos.tlcgoptGroupbox(4) + dy;
ctrlPos.addoptGroupbox(2)   = ctrlPos.addoptGroupbox(2)   + dy;

% define new height for addoptGroupbox
ctrlPos.addoptGroupbox(4) = 3 * commonGeom.editHeight ...
    + 2 * rowDelta ...
    + commonGeom.frameBottomEdgeBuffer ...
    + commonGeom.frameTopEdgeBuffer;

%-----------------------------------------------------------
% supplement tlcgGroupbox
%-----------------------------------------------------------
cy = ctrlPos.descLabel(2) + commonGeom.editHeight + rowDelta;

% select label
cx = col(1);
ctrlPos.selectLabel = [cx cy selectLabelSize];

% select popup
cx = col(2);
ctrlPos.selectPopup = [cx cy ctrlPos.lsbEdit(3:4)];

%-----------------------------------------------------------
% positions for table controls
%-----------------------------------------------------------
col(2) = col(1) + editLabelSize(1) + colDelta / 3;

%-----------------------------------------------------------
% 3rd row
cy = commonGeom.frameBottomEdgeBuffer;

%autoscale button
cx = col(1);
ctrlPos.autoscaleButton = [cx cy autoscaleButtonSize];

%-----------------------------------------------------------
% 2nd row
cy = cy + commonGeom.editHeight + rowDelta;

% ddv checkbox
cx = col(2);
ctrlPos.useDDValueCheckbox = [cx, cy, useDDValueCheckboxSize];

% outputmode popup
cx = col(5);
ctrlPos.outputmodePopup = [cx cy outputmodePopupSize];

% search algorithm popup
cx = col(4) + editLabelSize(1) + colDelta / 3;
ctrlPos.searchPopup = [cx cy ctrlPos.varEdit(3:4)];

%-----------------------------------------------------------
% 1st row
cy = cy + commonGeom.editHeight + rowDelta;

% table label
cx = col(1);
ctrlPos.uLabel = [cx cy editLabelSize];

% table edit field
cx = col(2);
ctrlPos.uEdit = [cx cy ctrlPos.varEdit(3:4)];

% search algorithm popup
cx = col(5);
ctrlPos.searchPopup = [cx cy ctrlPos.varEdit(3:4)];

% increase sheet dimensions
sheetDims(2) = sheetDims(2) ...
    + ctrlPos.addoptGroupbox(4) ...
    + commonGeom.textHeight ...
    + dy;


%-----------------------------------------------------------------------------------------
% FcnCreateTableCtrls creates controls of table page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateTableCtrls(pageNum, dlgfig, dlgdata)

Children = dlgdata.pageData{pageNum}.children;
ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;

% create the addoptGroupbox which will contain table options
Children.addoptGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Table options'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.addoptGroupbox);

% table  controls
Children.uLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Breakpoint data:', ...
    'Position',           ctrlPos.uLabel);

Children.uEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.uEdit);

Children.searchPopup = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'popupmenu', ...
    'BackgroundColor',    'w', ...
    'String',             {'Linear search, start low', ...
    'Linear search, start high', ...
    'Local search', ...
    'Binary search'}, ...
    'Position',           ctrlPos.searchPopup);

Children.useDDValueCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Use value of Data Dictionary variable', ...
    'Position',           ctrlPos.useDDValueCheckbox);

Children.outputmodePopup = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'popupmenu', ...
    'BackGroundColor',    'w', ...
    'Position',           ctrlPos.outputmodePopup);

% autoscale button
Children.autoscaleButton = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'pushbutton', ...
    'String',             'Scale Vector', ...
    'Position',           ctrlPos.autoscaleButton);

dlgdata.pageData{pageNum}.children  = Children;

% invoke standard functions to create variable and scaling controls
dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);

Children = dlgdata.pageData{pageNum}.children;

% selection popup
Children.selectLabel = uicontrol( ...
    'Parent',             Children.tlcgoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Select:', ...
    'Position',           ctrlPos.selectLabel);

Children.selectPopup = uicontrol( ...
    'Parent',             Children.tlcgoptGroupbox, ...
    'Style',              'Popupmenu', ...
    'BackgroundColor',    'w', ...
    'String',             {'breakpoint data', 'output'}, ...
    'Value',              1, ...
    'Position',           ctrlPos.selectPopup);

dlgdata.pageData{pageNum}.children = Children;


%-----------------------------------------------------------------------------------------
% FcnManageTableCtrls manage control actions of table page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageTableCtrls(pageNum, dlgfig, dlgdata, action)

bModified = false;
Children  = dlgdata.pageData{pageNum}.children;

switch action
    case 'uEdit'
        uStr = deblank(get(Children.uEdit, 'String'));
        if ~isempty(uStr)
            if strcmp(uStr, 'ddv')
                if isempty(dlgdata.data.input.variable)
                    beep;
                else
                    dlgdata.data.input.value = ['ddv(''', dlgdata.data.input.variable, ''')'];
                    dlgdata.data.input.useddvariablevalue = true;
                end
            else
                dlgdata.data.input.value = uStr;
            end
            bModified = true;
        else
            beep;
        end
        
    case 'useDDValueCheckbox'
        if get(Children.useDDValueCheckbox, 'Value')
            dlgdata.data.input.value = ['ddv(''', dlgdata.data.input.variable, ''')'];
            dlgdata.data.input.useddvariablevalue = true;
        else
            dlgdata.data.input.useddvariablevalue = false;
        end
        bModified = true;
        
    case 'autoscaleButton'
        ds_error_none;
        [dlgdata.data, bModified, msgstruct] = tl_scale_parameters( ...
            dlgdata.model, dlgdata.data);
        ds_error_register(msgstruct);
        ds_msgdlg('Update', ...
            'Title', ['Scaling of PreLook-up Index Search Block ' get_tlsubsystempath(dlgdata.model) ], ...
            'ShowErrors', 'yes', ...
            'ShowNotes', 'yes', ...
            'ShowWarnings', 'yes');
        
    case 'searchPopup'
        dlgdata.data.input.search = get(Children.searchPopup, 'Value');
        bModified = true;
        
    case 'selectPopup'
        bModified = true;
        
    case 'outputmodePopup'
        dlgdata.data.outputmode = get(Children.outputmodePopup, 'Value');
        bModified = true;
        
    otherwise
        selectIdx = get(Children.selectPopup, 'Value');
        vars = {'input', 'output'};
        field = vars{selectIdx};
        [dlgdata, bModified1] = TLManageVariableCtrls('manage', ...
            pageNum, dlgfig, dlgdata, action, field);
        [dlgdata, bModified2] = TLManageScalingCtrls('manage', ...
            pageNum, dlgfig, dlgdata, action, field, 1);

        bModified = bModified1 | bModified2;
end % switch(action)


%--------------------------------------------------------------------------
% FcnUpdateTableCtrls updates the controls of the table tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number (=1 for table page)
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateTableCtrls(pageNum, dlgfig, dlgdata)

Children = dlgdata.pageData{pageNum}.children;

% default control status
if dlgdata.bIsFullVs
    defaultStatus = 'on';
else
    defaultStatus = 'inactive';
end
% Update extra controls
% values and look-up method is independend of blockset mode
outputmodePopupCtrlStatus = struct('enable', 'on', 'value', 2);
searchPopupCtrlStatus = struct('enable', defaultStatus, ...
    'string', {{'Linear search, start low', ...
    'Linear search, start high', ...
    'Local search', ...
    'Binary search'}}, ...
    'value', 1);
selectPopupCtrlStatus = struct('enable', 'on', ...
    'string', {{'breakpoint data', 'output'}}, ...
    'value', 1);

selectIdx = get(Children.selectPopup, 'value');
switch selectIdx
    case 1
        field = 'input';
    case 2
        field = 'output';
end
selectPopupCtrlStatus.value = selectIdx;

% Update standard variable and scaling controls
dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, field);
[u, umin, umax, bCompliant] = tl_eval_table(dlgdata.data.input, true);
if ~bCompliant || selectIdx == 2
    constraint = [];
else
    % constraints from table data only if 'breakpoint data' is selected
    constraint = [umin umax];
end
dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, field, constraint);
% status of ddv checkbox
useDDValueCheckboxCtrlStatus.enable = flag2str(~isempty(dlgdata.data.input.variable));
useDDValueCheckboxCtrlStatus.value = dlgdata.data.input.useddvariablevalue;

uEditCtrlStatus = struct('enable', 'on', 'string', dlgdata.data.input.value);
if dlgdata.data.input.useddvariablevalue
    uEditCtrlStatus.enable = 'inactive';
end
uEditCtrlStatus.iserror = ~bCompliant;

% read ranges' CtrlStatus
simulatedLabelCtrlStatus = tl_get_control_userdata(Children.simulatedLabel);
upperSimulatedValueCtrlStatus = tl_get_control_userdata(Children.upperSimulatedValue);
lowerSimulatedValueCtrlStatus = tl_get_control_userdata(Children.lowerSimulatedValue);
calculatedLabelCtrlStatus = tl_get_control_userdata(Children.calculatedLabel);
upperCalculatedValueCtrlStatus = tl_get_control_userdata(Children.upperCalculatedValue);
lowerCalculatedValueCtrlStatus = tl_get_control_userdata(Children.lowerCalculatedValue);

% adjust some of the standard controls
widthEditCtrlStatus = tl_get_control_userdata(Children.widthEdit);
widthUpButtonCtrlStatus = tl_get_control_userdata(Children.widthUpButton);
widthDownButtonCtrlStatus = tl_get_control_userdata(Children.widthDownButton);

switch selectIdx
    case 1
        % breakpoint data
        % update production code options for breakpoint data variable
        if ~isempty(u) && bCompliant
            minstr = sprintf('%0.5g', umin);
            maxstr = sprintf('%0.5g', umax);
        else
            minstr = 'n.a.';
            maxstr = 'n.a.';
        end
        simulatedLabelCtrlStatus.string = 'of vector';
        upperSimulatedValueCtrlStatus.string = maxstr;
        lowerSimulatedValueCtrlStatus.string = minstr;
        calculatedLabelCtrlStatus.enable = 'off';
        upperCalculatedValueCtrlStatus.string = '';
        lowerCalculatedValueCtrlStatus.string = '';
    case 2
        % output
        widthEditCtrlStatus.enable = 'inactive';
        widthUpButtonCtrlStatus.enable = 'off';
        widthDownButtonCtrlStatus.enable = 'off';
        simulatedLabelCtrlStatus.string = 'Simulated';
end

baseType = dsdd('GetBaseType', ['/Pool/Typedefs/' dlgdata.data.output.type]);
nBytes = get_nbytes(baseType);
blockConfig = tl_get_block_config(dlgdata.model);
neededBits = blockConfig.fractionStartBit + blockConfig.fractionNumBits;
if ds_isa(baseType, 'integertype') && ~isempty(nBytes) && (nBytes * 8 >= neededBits),
    outputModeStr = { ...
        'Output only the index', ...
        'Separate output variables for index and fraction', ...
        'Common output variable for index and fraction'};
else
    outputModeStr = { ...
        'Output only the index', ...
        'Separate output variables for index and fraction'};
    dlgdata.data.outputmode = min(dlgdata.data.outputmode, 2);
end
outputmodePopupCtrlStatus.string = outputModeStr;
outputmodePopupCtrlStatus.value = dlgdata.data.outputmode;
searchPopupCtrlStatus.value = dlgdata.data.input.search;

autoscaleButtonCtrlStatus = struct('enable', defaultStatus);
% activation of 'Scale Table' button
% special behaviour of table blocks: Scale button must be disabled if 'no
% autoscaling' is selected
bOutputInteger = ds_isa(['/Pool/Typedefs/' dlgdata.data.output.type], 'integertype');
bAutoscEnable = bOutputInteger ...
    && isempty(dsdd('GetConstraintsScalingRef', ['/Pool/Typedefs/' dlgdata.data.output.type])) ...
    && isempty(dlgdata.data.output.scaling);
bScaleButtonEnable  = dlgdata.bIsFullVs && bAutoscEnable && dlgdata.data.autoscaling.mode == 1;
autoscaleButtonCtrlStatus.enable = flag2str(bScaleButtonEnable);

% set control status
extraCtrlsList = {
    'autoscaleButton' ...
    'uEdit' ...
    'useDDValueCheckbox' ...
    'outputmodePopup' ...
    'selectPopup' ...
    'searchPopup'};
standardCtrlsList = {
    'calculatedLabel' ...
    'upperCalculatedValue' ...
    'lowerCalculatedValue' ...
    'simulatedLabel' ...
    'upperSimulatedValue' ...
    'lowerSimulatedValue' ...
    'widthEdit' ...
    'widthUpButton' ...
    'widthDownButton' ...
    };
ctrlsList = [extraCtrlsList standardCtrlsList];
for ctrlsNo=1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set control status of variable, scaling and table parameter groupbox controls
TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLSetCtrlsStatus(dlgfig, Children, extraCtrlsList);


%-----------------------------------------------------------------------------------------
% FcnCreateDocumentationCtrls create controls of documentation page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateDocumentationCtrls(pageNum, dlgfig, dlgdata)

% invoke generic function to create documentation page
dlgdata = TLManageDocCtrls('create',pageNum,dlgfig,dlgdata);

% create additional controls
Children = dlgdata.pageData{pageNum}.children;
ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;
Children.tblFcnName   = uicontrol( ...
    'Parent',            dlgfig, ...
    'Style',             'text', ...
    'String',            'Table function name: n.a.', ...
    'Position',          ctrlPos.tblFcnName);
Children.clipboardButton = uicontrol( ...
    'Parent',            dlgfig, ...
    'Style',             'pushbutton', ...
    'String',            'Copy to Clipboard', ...
    'Position',          ctrlPos.clipboardButton);

% save extended children handle structure
dlgdata.pageData{pageNum}.children = Children;


%-----------------------------------------------------------------------------------------
% FcnManageDocumentationCtrls manage control actions of documentation page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata,bModified] = FcnManageDocumentationCtrls(pageNum, dlgfig, dlgdata, pageAction)

% default return value
bModified = false;

% clipboard callbacks are handled directly here
if strcmp(pageAction, 'clipboardButton')
    clipboard('copy', dlgdata.pageData{pageNum}.tblFcnName);
    return
end

% invoke generic function to manage control callbacks
[dlgdata, bModified] = TLManageDocCtrls('callback', pageNum, dlgfig, ...
    dlgdata,pageAction);


%--------------------------------------------------------------------------
% FcnUpdateDocumentationCtrls updates the controls of the documentation tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number (=1 for table page)
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateDocumentationCtrls(pageNum, dlgfig, dlgdata)

TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);

Children = dlgdata.pageData{pageNum}.children;
t = tl_eval_table(dlgdata.data.input, true);

tblFcnName = 'n.a.';
if ~isempty(t)
    % invoke get_plktabledata in batch mode
    b = ds_error_get('batchmode');
    ds_error_set('batchmode', 'on');
    [tableData,msgstruct] = get_plktabledata(dlgdata.data, t, inf);
    ds_error_set('batchmode',b);

    % determine tablefunction name
    if isempty(msgstruct) || ~any(strcmp({msgstruct.type}, 'Error'))
        tblFcnName = tl_get_tblfcnnames( ...
            dlgdata.data, dlgdata.model, tableData, dlgdata.maskType);
    end
    if iscell(tblFcnName)
        tblFcnName = [tblFcnName{:}];
    end
end

tblFcnNameCtrlStatus = struct('enable', 'on');
clipboardButtonCtrlStatus = struct('enable', 'on');
tblFcnNameCtrlStatus.string = sprintf('Table function name: %s', tblFcnName);
clipboardButtonCtrlStatus.enable = flag2str(~isempty(tblFcnName) && ~strcmp(tblFcnName, 'n.a.'));
ctrlsList = {'tblFcnName', 'clipboardButton'};
for ctrlsNo=1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end
TLSetCtrlsStatus(dlgfig, Children, ctrlsList);

% save table function name at dialog data structure
dlgdata.pageData{pageNum}.tblFcnName = tblFcnName;
